package aliyun

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/util/gconv"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/green"
	"github.com/gogf/gf/v2/frame/g"
)

func NewYundun(ctx context.Context) *yundun {
	var aliyunConfig *aliyunConfig
	err := g.Config().MustGet(ctx, "org.aliyun").Struct(&aliyunConfig)
	if err != nil {
		panic(err)
	}
	fmt.Println(aliyunConfig)

	client, err := green.NewClientWithAccessKey(aliyunConfig.Region, aliyunConfig.AccessId, aliyunConfig.AccessKey)
	if err != nil {
		panic(err)
	}

	return &yundun{
		ctx: ctx,

		client: client,
	}
}

type yundun struct {
	ctx context.Context

	client *green.Client

	Tasks []*textSyncTask `json:"tasks"`
}
type textSyncTask struct {
	ClientInfo interface{} `json:"clientInfo,omitempty"`
	DataId     *string     `json:"dataId"`
	Content    string      `json:"content"`
}

func (r *yundun) Add(dataId *string, content string) *yundun {
	r.Tasks = append(r.Tasks, &textSyncTask{
		DataId:  dataId,
		Content: content,
	})

	return r
}
func (r *yundun) TextScan() *textSyncResp {
	request := green.CreateTextScanRequest()
	bs, err := gjson.Encode(*r)
	if err != nil {
		panic(err)
	}
	request.SetContent(bs)

	response, err := r.client.TextScan(request)
	if err != nil {
		panic(err)
	}

	var res *textSyncResp
	err = gconv.Scan(response.GetHttpContentBytes(), &res)
	if err != nil {
		panic(err)
	}

	return res
}
